<template>
  <!-- 
    模块管理面板组件
    功能：
    1. 显示所有可用模块
    2. 管理模块的启用/禁用状态
    3. 提供模块搜索和筛选功能
    4. 显示模块统计信息
    5. 提供批量操作功能
  -->
  <div class="module-management-panel">
    <!-- 面板头部 -->
    <div class="panel-header">
      <div class="header-left">
        <h2 class="panel-title">
          <el-icon><Setting /></el-icon>
          模块管理
        </h2>
        <div class="header-stats">
          <el-tag type="info" size="small">
            总计: {{ moduleStats.total }}
          </el-tag>
          <el-tag type="success" size="small">
            已加载: {{ moduleStats.loaded }}
          </el-tag>
          <el-tag type="primary" size="small">
            已启用: {{ moduleStats.enabled }}
          </el-tag>
          <el-tag type="warning" size="small">
            加载中: {{ moduleStats.loading }}
          </el-tag>
          <el-tag type="danger" size="small">
            错误: {{ moduleStats.error }}
          </el-tag>
        </div>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button 
            type="primary" 
            @click="refreshModules"
            :loading="refreshing"
            size="small"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button 
            @click="showSystemStats = true"
            size="small"
          >
            <el-icon><DataLine /></el-icon>
            统计
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索模块..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-controls">
        <el-select
          v-model="selectedCategory"
          placeholder="按分类筛选"
          clearable
          @change="handleCategoryFilter"
          size="small"
        >
          <el-option
            v-for="category in availableCategories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
        
        <el-select
          v-model="statusFilter"
          placeholder="按状态筛选"
          clearable
          @change="handleStatusFilter"
          size="small"
        >
          <el-option label="已加载" value="loaded" />
          <el-option label="未加载" value="unloaded" />
          <el-option label="加载中" value="loading" />
          <el-option label="错误" value="error" />
          <el-option label="已启用" value="enabled" />
          <el-option label="已禁用" value="disabled" />
        </el-select>
      </div>
    </div>

    <!-- 批量操作区域 -->
    <div v-if="selectedModules.size > 0" class="batch-actions">
      <div class="batch-info">
        <span>已选择 {{ selectedModules.size }} 个模块</span>
        <el-button size="small" text @click="clearSelection">清除选择</el-button>
      </div>
      <div class="batch-buttons">
        <el-button 
          type="primary" 
          size="small"
          @click="batchEnableModules"
          :loading="batchOperating"
        >
          批量启用
        </el-button>
        <el-button 
          type="warning" 
          size="small"
          @click="batchDisableModules"
          :loading="batchOperating"
        >
          批量禁用
        </el-button>
        <el-button 
          type="success" 
          size="small"
          @click="batchLoadModules"
          :loading="batchOperating"
        >
          批量加载
        </el-button>
        <el-button 
          type="danger" 
          size="small"
          @click="batchUnloadModules"
          :loading="batchOperating"
        >
          批量卸载
        </el-button>
      </div>
    </div>

    <!-- 模块列表 -->
    <div class="module-list">
      <el-table
        :data="filteredModules"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        style="width: 100%"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="55" />
        
        <!-- 模块信息列 -->
        <el-table-column label="模块信息" min-width="300">
          <template #default="{ row }">
            <div class="module-info-cell">
              <div class="module-icon">
                <el-icon 
                  :size="24" 
                  :color="getModuleColor(row.category)"
                >
                  <component :is="getModuleIcon(row.category)" />
                </el-icon>
              </div>
              <div class="module-details">
                <div class="module-name">{{ row.name }}</div>
                <div class="module-description">{{ row.description }}</div>
                <div class="module-meta">
                  <el-tag size="small" :type="getModuleTagType(row.category)">
                    {{ row.category }}
                  </el-tag>
                  <span class="module-version">v{{ row.version }}</span>
                  <span class="module-author">by {{ row.author }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 状态列 -->
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <div class="module-status">
              <el-tag 
                :type="getStatusTagType(getModuleStatus(row.id))"
                size="small"
              >
                {{ getStatusText(getModuleStatus(row.id)) }}
              </el-tag>
              <div v-if="moduleStore.getModuleError(row.id)" class="error-indicator">
                <el-tooltip :content="moduleStore.getModuleError(row.id)" placement="top">
                  <el-icon color="#F56C6C" size="14">
                    <WarningFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="module-actions">
              <!-- 启用/禁用按钮 -->
              <el-switch
                v-model="moduleEnabledStates[row.id]"
                @change="handleModuleToggle(row.id, $event)"
                :loading="moduleOperatingStates[row.id]"
                size="small"
                inline-prompt
                active-text="启用"
                inactive-text="禁用"
              />
              
              <!-- 加载/卸载按钮 -->
              <el-button-group size="small">
                <el-button
                  v-if="!moduleStore.isModuleLoaded(row.id)"
                  type="success"
                  @click="loadSingleModule(row.id)"
                  :loading="moduleOperatingStates[row.id]"
                  size="small"
                  title="加载模块"
                >
                  <el-icon><Download /></el-icon>
                </el-button>
                <el-button
                  v-else
                  type="warning"
                  @click="unloadSingleModule(row.id)"
                  :loading="moduleOperatingStates[row.id]"
                  size="small"
                  title="卸载模块"
                >
                  <el-icon><Upload /></el-icon>
                </el-button>
                
                <!-- 配置按钮 -->
                <el-button
                  @click="showModuleConfig(row)"
                  size="small"
                  title="配置模块"
                >
                  <el-icon><Setting /></el-icon>
                </el-button>
                
                <!-- 详情按钮 -->
                <el-button
                  @click="showModuleDetails(row)"
                  size="small"
                  title="模块详情"
                >
                  <el-icon><InfoFilled /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 系统统计对话框 -->
    <el-dialog
      v-model="showSystemStats"
      title="系统统计信息"
      width="800px"
    >
      <div class="system-stats-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>模块统计</span>
              </template>
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-value">{{ moduleStats.total }}</div>
                  <div class="stat-label">总模块数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ moduleStats.loaded }}</div>
                  <div class="stat-label">已加载</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ moduleStats.enabled }}</div>
                  <div class="stat-label">已启用</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ moduleStats.error }}</div>
                  <div class="stat-label">错误</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>性能指标</span>
              </template>
              <div class="performance-stats">
                <div class="performance-item">
                  <span class="performance-label">平均加载时间:</span>
                  <span class="performance-value">{{ systemStats.performance.averageLoadTime?.toFixed(2) || 0 }}ms</span>
                </div>
                <div class="performance-item">
                  <span class="performance-label">总错误数:</span>
                  <span class="performance-value">{{ systemStats.performance.totalErrors || 0 }}</span>
                </div>
                <div class="performance-item">
                  <span class="performance-label">缓存命中率:</span>
                  <span class="performance-value">{{ (systemStats.storage.hitRate || 0).toFixed(1) }}%</span>
                </div>
                <div class="performance-item">
                  <span class="performance-label">缓存条目:</span>
                  <span class="performance-value">{{ systemStats.storage.totalEntries || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 模块配置对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="`配置 ${selectedModuleForConfig?.name}`"
      width="600px"
    >
      <div class="config-content">
        <el-form
          ref="configFormRef"
          :model="configForm"
          :rules="configRules"
          label-width="120px"
        >
          <el-form-item label="模块配置" prop="config">
            <el-input
              v-model="configForm.config"
              type="textarea"
              :rows="10"
              placeholder="请输入JSON格式的模块配置"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConfigDialog = false">取消</el-button>
          <el-button type="primary" @click="saveModuleConfig" :loading="savingConfig">
            保存配置
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模块详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      :title="`${selectedModuleForDetails?.name} 详情`"
      width="700px"
    >
      <div class="module-details-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模块名称">
            {{ selectedModuleForDetails?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            {{ selectedModuleForDetails?.version }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getModuleTagType(selectedModuleForDetails?.category)">
              {{ selectedModuleForDetails?.category }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="作者">
            {{ selectedModuleForDetails?.author }}
          </el-descriptions-item>
          <el-descriptions-item label="入口文件">
            {{ selectedModuleForDetails?.entry }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(getModuleStatus(selectedModuleForDetails?.id))">
              {{ getStatusText(getModuleStatus(selectedModuleForDetails?.id)) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ selectedModuleForDetails?.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ selectedModuleForDetails?.updated_at }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="module-description-section">
          <h4>描述</h4>
          <p>{{ selectedModuleForDetails?.description }}</p>
        </div>
        
        <div v-if="selectedModuleForDetails?.dependencies" class="module-dependencies">
          <h4>依赖模块</h4>
          <div class="dependency-tags">
            <el-tag
              v-for="dep in selectedModuleForDetails.dependencies"
              :key="dep"
              :type="moduleStore.isModuleLoaded(dep) ? 'success' : 'info'"
              size="small"
            >
              {{ dep }}
            </el-tag>
          </div>
        </div>
        
        <div v-if="selectedModuleForDetails?.id && moduleStore.getModuleErrorHistory(selectedModuleForDetails?.id).length > 0" class="module-error-history">
          <h4>错误历史</h4>
          <el-timeline>
            <el-timeline-item
              v-for="error in moduleStore.getModuleErrorHistory(selectedModuleForDetails?.id)"
              :key="error.timestamp"
              :timestamp="new Date(error.timestamp).toLocaleString()"
              type="danger"
            >
              <div class="error-item">
                <div class="error-type">{{ error.errorType }}</div>
                <div class="error-message">{{ error.errorMessage }}</div>
                <div v-if="error.retryCount" class="error-retries">
                  重试次数: {{ error.retryCount }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 模块管理面板组件
 * 
 * 功能：
 * 1. 显示所有可用模块
 * 2. 管理模块的启用/禁用状态
 * 3. 提供模块搜索和筛选功能
 * 4. 显示模块统计信息
 * 5. 提供批量操作功能
 */

import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { 
  Setting, 
  Refresh, 
  DataLine, 
  Search,
  Grid,
  Monitor,
  Message,
  Document,
  VideoPlay,
  Download,
  Upload,
  InfoFilled,
  WarningFilled
} from '@element-plus/icons-vue'
import { useModuleStore } from '@/stores/module'
import type { DynamicModule, ModuleConfig } from '@/modules/dynamic/types'

// ==================== 依赖注入 ====================
const moduleStore = useModuleStore()

// ==================== 响应式状态 ====================
/** 加载状态 */
const loading = ref(false)
/** 刷新状态 */
const refreshing = ref(false)
/** 批量操作状态 */
const batchOperating = ref(false)
/** 保存配置状态 */
const savingConfig = ref(false)

/** 搜索查询 */
const searchQuery = ref('')
/** 选中的分类 */
const selectedCategory = ref('')
/** 状态筛选 */
const statusFilter = ref('')

/** 选中的模块 */
const selectedModules = ref<Set<string>>(new Set())
/** 模块启用状态 */
const moduleEnabledStates = ref<Record<string, boolean>>({})
/** 模块操作状态 */
const moduleOperatingStates = ref<Record<string, boolean>>({})

/** 对话框状态 */
const showSystemStats = ref(false)
const showConfigDialog = ref(false)
const showDetailsDialog = ref(false)

/** 选中的模块 */
const selectedModuleForConfig = ref<DynamicModule | null>(null)
const selectedModuleForDetails = ref<DynamicModule | null>(null)

/** 配置表单 */
const configFormRef = ref<FormInstance>()
const configForm = ref({
  config: '{}'
})

/** 配置表单验证规则 */
const configRules: FormRules = {
  config: [
    { required: true, message: '请输入模块配置', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        try {
          JSON.parse(value)
          callback()
        } catch (error) {
          callback(new Error('请输入有效的JSON格式'))
        }
      },
      trigger: 'blur'
    }
  ]
}

// ==================== 计算属性 ====================
/** 模块统计信息 */
const moduleStats = computed(() => moduleStore.moduleStats)

/** 系统统计信息 */
const systemStats = computed(() => moduleStore.getSystemStats())

/** 可用分类 */
const availableCategories = computed(() => moduleStore.availableCategories)

/** 过滤后的模块列表 */
const filteredModules = computed(() => {
  let modules = moduleStore.modules

  // 搜索筛选
  if (searchQuery.value) {
    modules = moduleStore.searchModules(searchQuery.value)
  }

  // 分类筛选
  if (selectedCategory.value) {
    modules = moduleStore.getModulesByCategory(selectedCategory.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    modules = modules.filter(module => {
      const status = getModuleStatus(module.id)
      switch (statusFilter.value) {
        case 'loaded':
          return status === 'loaded'
        case 'unloaded':
          return status === 'unloaded'
        case 'loading':
          return status === 'loading'
        case 'error':
          return status === 'error'
        case 'enabled':
          return moduleStore.isModuleEnabled(module.id)
        case 'disabled':
          return !moduleStore.isModuleEnabled(module.id)
        default:
          return true
      }
    })
  }

  return modules
})

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  await initializePanel()
})

/**
 * 组件卸载时清理
 */
onUnmounted(() => {
  cleanupPanel()
})

// ==================== 初始化方法 ====================
/**
 * 初始化面板
 */
async function initializePanel() {
  try {
    loading.value = true
    await moduleStore.initialize()
    updateModuleStates()
  } catch (error) {
    console.error('Failed to initialize module management panel:', error)
    ElMessage.error('初始化模块管理面板失败')
  } finally {
    loading.value = false
  }
}

/**
 * 清理面板
 */
function cleanupPanel() {
  // 清理定时器等资源
}

// ==================== 数据更新方法 ====================
/**
 * 更新模块状态
 */
function updateModuleStates() {
  const enabledStates: Record<string, boolean> = {}
  const operatingStates: Record<string, boolean> = {}

  moduleStore.modules.forEach(module => {
    enabledStates[module.id] = moduleStore.isModuleEnabled(module.id)
    operatingStates[module.id] = false
  })

  moduleEnabledStates.value = enabledStates
  moduleOperatingStates.value = operatingStates
}

// ==================== 事件处理方法 ====================
/**
 * 刷新模块列表
 */
async function refreshModules() {
  try {
    refreshing.value = true
    await moduleStore.fetchAvailableModules()
    updateModuleStates()
    ElMessage.success('模块列表已刷新')
  } catch (error) {
    console.error('Failed to refresh modules:', error)
    ElMessage.error('刷新模块列表失败')
  } finally {
    refreshing.value = false
  }
}

/**
 * 处理搜索
 */
function handleSearch() {
  // 搜索是响应式的，不需要额外处理
}

/**
 * 处理分类筛选
 */
function handleCategoryFilter() {
  // 筛选是响应式的，不需要额外处理
}

/**
 * 处理状态筛选
 */
function handleStatusFilter() {
  // 筛选是响应式的，不需要额外处理
}

/**
 * 处理选择变化
 */
function handleSelectionChange(selection: DynamicModule[]) {
  selectedModules.value = new Set(selection.map(m => m.id))
}

/**
 * 处理排序变化
 */
function handleSortChange() {
  // 可以在这里添加排序逻辑
}

/**
 * 清除选择
 */
function clearSelection() {
  selectedModules.value.clear()
}

// ==================== 批量操作方法 ====================
/**
 * 批量启用模块
 */
async function batchEnableModules() {
  try {
    batchOperating.value = true
    const moduleIds = Array.from(selectedModules.value)
    await Promise.all(moduleIds.map(id => moduleStore.enableModule(id)))
    updateModuleStates()
    ElMessage.success(`已启用 ${moduleIds.length} 个模块`)
    clearSelection()
  } catch (error) {
    console.error('Failed to batch enable modules:', error)
    ElMessage.error('批量启用模块失败')
  } finally {
    batchOperating.value = false
  }
}

/**
 * 批量禁用模块
 */
async function batchDisableModules() {
  try {
    batchOperating.value = true
    const moduleIds = Array.from(selectedModules.value)
    await Promise.all(moduleIds.map(id => moduleStore.disableModule(id)))
    updateModuleStates()
    ElMessage.success(`已禁用 ${moduleIds.length} 个模块`)
    clearSelection()
  } catch (error) {
    console.error('Failed to batch disable modules:', error)
    ElMessage.error('批量禁用模块失败')
  } finally {
    batchOperating.value = false
  }
}

/**
 * 批量加载模块
 */
async function batchLoadModules() {
  try {
    batchOperating.value = true
    const moduleIds = Array.from(selectedModules.value)
    await moduleStore.loadModules(moduleIds)
    ElMessage.success(`已加载 ${moduleIds.length} 个模块`)
    clearSelection()
  } catch (error) {
    console.error('Failed to batch load modules:', error)
    ElMessage.error('批量加载模块失败')
  } finally {
    batchOperating.value = false
  }
}

/**
 * 批量卸载模块
 */
async function batchUnloadModules() {
  try {
    batchOperating.value = true
    const moduleIds = Array.from(selectedModules.value)
    await moduleStore.unloadModules(moduleIds)
    ElMessage.success(`已卸载 ${moduleIds.length} 个模块`)
    clearSelection()
  } catch (error) {
    console.error('Failed to batch unload modules:', error)
    ElMessage.error('批量卸载模块失败')
  } finally {
    batchOperating.value = false
  }
}

// ==================== 单个模块操作方法 ====================
/**
 * 处理模块启用/禁用切换
 */
async function handleModuleToggle(moduleId: string, enabled: boolean) {
  try {
    moduleOperatingStates.value[moduleId] = true
    
    if (enabled) {
      await moduleStore.enableModule(moduleId)
      ElMessage.success('模块已启用')
    } else {
      await moduleStore.disableModule(moduleId)
      ElMessage.success('模块已禁用')
    }
  } catch (error) {
    console.error('Failed to toggle module:', error)
    ElMessage.error('操作失败，已恢复原状态')
    // 恢复开关状态
    moduleEnabledStates.value[moduleId] = !enabled
  } finally {
    moduleOperatingStates.value[moduleId] = false
  }
}

/**
 * 加载单个模块
 */
async function loadSingleModule(moduleId: string) {
  try {
    moduleOperatingStates.value[moduleId] = true
    await moduleStore.loadModule(moduleId)
    ElMessage.success('模块加载成功')
  } catch (error) {
    console.error('Failed to load module:', error)
    ElMessage.error('模块加载失败')
  } finally {
    moduleOperatingStates.value[moduleId] = false
  }
}

/**
 * 卸载单个模块
 */
async function unloadSingleModule(moduleId: string) {
  try {
    moduleOperatingStates.value[moduleId] = true
    await moduleStore.unloadModule(moduleId)
    ElMessage.success('模块卸载成功')
  } catch (error) {
    console.error('Failed to unload module:', error)
    ElMessage.error('模块卸载失败')
  } finally {
    moduleOperatingStates.value[moduleId] = false
  }
}

// ==================== 对话框方法 ====================
/**
 * 显示模块配置
 */
function showModuleConfig(module: DynamicModule) {
  selectedModuleForConfig.value = module
  const currentConfig = moduleStore.getModuleConfig(module.id)
  configForm.value.config = JSON.stringify(currentConfig, null, 2)
  showConfigDialog.value = true
}

/**
 * 保存模块配置
 */
async function saveModuleConfig() {
  if (!configFormRef.value || !selectedModuleForConfig.value) return
  
  try {
    await configFormRef.value.validate()
    savingConfig.value = true
    
    // 解析配置
    const config = JSON.parse(configForm.value.config)
    
    // 更新模块配置
    moduleStore.setModuleConfig(selectedModuleForConfig.value.id, config)
    
    showConfigDialog.value = false
    ElMessage.success('模块配置已保存')
  } catch (error) {
    ElMessage.error('保存配置失败: ' + (error instanceof Error ? error.message : 'Unknown error'))
  } finally {
    savingConfig.value = false
  }
}

/**
 * 显示模块详情
 */
function showModuleDetails(module: DynamicModule) {
  selectedModuleForDetails.value = module
  showDetailsDialog.value = true
}

// ==================== 辅助方法 ====================
/**
 * 获取模块状态
 */
function getModuleStatus(moduleId: string): 'loading' | 'loaded' | 'error' | 'unloaded' {
  return moduleStore.getModuleLoadState(moduleId)
}

/**
 * 获取状态标签类型
 */
function getStatusTagType(status: string): string {
  const typeMap: Record<string, string> = {
    'loaded': 'success',
    'loading': 'warning',
    'error': 'danger',
    'unloaded': 'info'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
function getStatusText(status: string): string {
  const textMap: Record<string, string> = {
    'loaded': '已加载',
    'loading': '加载中',
    'error': '错误',
    'unloaded': '未加载'
  }
  return textMap[status] || '未知'
}

/**
 * 根据模块分类获取对应的图标
 */
function getModuleIcon(category?: string): string {
  const iconMap: Record<string, any> = {
    'default': Grid,
    'system': Setting,
    'tool': Setting,
    'dashboard': Monitor,
    'communication': Message,
    'file': Document,
    'entertainment': VideoPlay
  }
  return iconMap[category || 'default'] || Grid
}

/**
 * 根据模块分类获取对应的颜色
 */
function getModuleColor(category?: string): string {
  const colorMap: Record<string, string> = {
    'default': '#409EFF',
    'system': '#909399',
    'tool': '#E6A23C',
    'dashboard': '#67C23A',
    'communication': '#8B5CF6',
    'file': '#F56C6C',
    'entertainment': '#FF6B6B'
  }
  return colorMap[category || 'default'] || '#409EFF'
}

/**
 * 根据模块分类获取对应的标签类型
 */
function getModuleTagType(category?: string): string {
  const typeMap: Record<string, string> = {
    'default': 'primary',
    'system': 'info',
    'tool': 'warning',
    'dashboard': 'success',
    'communication': 'danger',
    'file': 'danger',
    'entertainment': 'danger'
  }
  return typeMap[category || 'default'] || 'primary'
}

// ==================== 监听器 ====================
/**
 * 监听模块列表变化
 */
watch(() => moduleStore.modules, () => {
  updateModuleStates()
}, { deep: true })
</script>

<style scoped>
.module-management-panel {
  padding: 20px;
  background: var(--bg-color);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-color);
}

/* 面板头部 */
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-color);
}

.header-stats {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 搜索和筛选区域 */
.search-filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-bar {
  flex: 1;
  min-width: 200px;
}

.filter-controls {
  display: flex;
  gap: 12px;
}

/* 批量操作区域 */
.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 20px;
  background: var(--bg-color-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-color);
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 模块列表 */
.module-list {
  background: var(--card-bg);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-color);
  overflow: hidden;
}

/* 模块信息单元格 */
.module-info-cell {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.module-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.module-details {
  flex: 1;
  min-width: 0;
}

.module-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 4px;
}

.module-description {
  font-size: 14px;
  color: var(--text-color-secondary);
  margin-bottom: 8px;
  line-height: 1.4;
}

.module-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.module-version {
  font-size: 12px;
  color: var(--text-color-tertiary);
}

.module-author {
  font-size: 12px;
  color: var(--text-color-tertiary);
}

/* 模块状态 */
.module-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-indicator {
  cursor: pointer;
}

/* 模块操作 */
.module-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 系统统计内容 */
.system-stats-content {
  padding: 20px 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: var(--bg-color-secondary);
  border-radius: var(--radius-md);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.performance-stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.performance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--border-color);
}

.performance-item:last-child {
  border-bottom: none;
}

.performance-label {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.performance-value {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
}

/* 配置内容 */
.config-content {
  padding: 20px 0;
}

/* 模块详情内容 */
.module-details-content {
  padding: 20px 0;
}

.module-description-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.module-description-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.module-description-section p {
  margin: 0;
  font-size: 14px;
  line-height: 1.6;
  color: var(--text-color-secondary);
}

.module-dependencies {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.module-dependencies h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.dependency-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.module-error-history {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.module-error-history h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.error-item {
  padding: 8px 12px;
  background: var(--bg-color-secondary);
  border-radius: var(--radius-md);
  border-left: 3px solid var(--error-color);
}

.error-type {
  font-size: 12px;
  font-weight: 600;
  color: var(--error-color);
  margin-bottom: 4px;
}

.error-message {
  font-size: 14px;
  color: var(--text-color-secondary);
  margin-bottom: 4px;
  word-break: break-word;
}

.error-retries {
  font-size: 12px;
  color: var(--text-color-tertiary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .module-management-panel {
    padding: 16px;
  }
  
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    flex-direction: column;
  }
  
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .batch-buttons {
    flex-wrap: wrap;
  }
  
  .module-info-cell {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .module-actions {
    flex-wrap: wrap;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .module-management-panel {
    background: var(--bg-color);
    border-color: var(--border-color);
  }
  
  .panel-header {
    border-color: var(--border-color);
  }
  
  .batch-actions {
    background: var(--bg-color);
    border-color: var(--border-color);
  }
  
  .module-list {
    background: var(--card-bg);
    border-color: var(--border-color);
  }
}
</style>
